import md5
import urllib
import mimetypes
import wsgiref.handlers
import logging

from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.api import urlfetch
from google.appengine.ext import db

from Img import Img
import utils.imageutils as imageutils
from Img import NotSupportedImageEncodingError

import logging

class storeimg(webapp.RequestHandler):
    def post(self):
        user = users.get_current_user()

        error = ''
        msg = ''
        while True:
            if not user:
                #self.redirect(users.create_login_url(urllib.unquote_plus(self.request.uri)))
                error = 'need login to store image'
                break
##             filename = self.request.params['filetoupload'].filename
##             contenttype = mimetypes.guess_type(filename)[0]
            image = self.request.get('filetoupload')
            if len(image) < 4:
                error = 'image file too small'
                break
            if len(image) > 1024*1024:
                error = 'image file too large ( should be <=1M)'
                break
            #get thumbnail first
            try:
                tb,contenttype = imageutils.thumbnailimage(image)
            except NotSupportedImageEncodingError:
                #not supported encoding
                self.redirect('/error/' + 'The file is not a supported encoding image')
                return
            #is image, we compute md5sum
            imgId = md5.new(image).hexdigest()
            msg = imgId
            if len(Img.all().filter('imgId = ',imgId).fetch(1)) == 0:
                #not exists
                img = Img(uploader = user,
                          imgId = imgId,
                          contentType = contenttype,
                          contentLength = len(image),
                          content = image,
                          thumbnail = tb,
                          accessTimes = 0,
                          originalURL = user.email()
                          )
                #we save it to db
                img.put()
            break
        self.response.headers['Content-Type']='text/html'
        self.response.out.write('{error: \'%s\',\nmsg:\'%s\'\n}' % (error, msg))
        return
        
def main():
    application = webapp.WSGIApplication(
                           [('/store/', storeimg)],
                           debug=True)
    wsgiref.handlers.CGIHandler().run(application)

if __name__ == '__main__':
    main()

